from flask import Flask, request, jsonify
from flask_cors import CORS
from werkzeug.utils import secure_filename
import os
import subprocess
from pathlib import Path
import tempfile
import requests
import json
import threading
import time

app = Flask(__name__)
CORS(app)  # Enable CORS for all routes

app.config['UPLOAD_FOLDER'] = tempfile.gettempdir()
app.config['MAX_CONTENT_LENGTH'] = 1024 * 1024 * 1024  # 1GB max file size

class AABInstaller:
    def __init__(self):
        self.bundletool_path = "bundletool.jar"
        self._check_bundletool()
    
    def _check_bundletool(self):
        if not os.path.exists(self.bundletool_path):
            raise FileNotFoundError("未找到 bundletool.jar")

    def convert_to_apks(self, aab_path: str) -> str:
        output_path = str(Path(aab_path).with_suffix('.apks'))
        cmd = [
            "java", "-jar", self.bundletool_path,
            "build-apks",
            f"--bundle={aab_path}",
            f"--output={output_path}",
            "--mode=universal"
        ]
        try:
            result = subprocess.run(
                cmd, 
                check=True,
                capture_output=True,
                text=True
            )
            return output_path
        except subprocess.CalledProcessError as e:
            error_msg = f"Bundletool 错误:\n标准输出: {e.stdout}\n错误输出: {e.stderr}"
            raise RuntimeError(error_msg)

    def install_apks(self, apks_path: str, device_id: str = None):
        cmd = [
            "java", "-jar", self.bundletool_path,
            "install-apks",
            f"--apks={apks_path}"
        ]
        if device_id:
            cmd.append(f"--device-id={device_id}")
        try:
            result = subprocess.run(
                cmd, 
                check=True,
                capture_output=True,
                text=True
            )
        except subprocess.CalledProcessError as e:
            error_msg = f"安装错误:\n标准输出: {e.stdout}\n错误输出: {e.stderr}"
            raise RuntimeError(error_msg)

# 添加设备监听类
class DeviceMonitor:
    def __init__(self):
        self._devices = set()
        self._callbacks = []
        self._running = False
        self._thread = None

    def start(self):
        if not self._running:
            self._running = True
            self._thread = threading.Thread(target=self._monitor_devices)
            self._thread.daemon = True
            self._thread.start()

    def stop(self):
        self._running = False
        if self._thread:
            self._thread.join()

    def _monitor_devices(self):
        while self._running:
            try:
                result = subprocess.run(['adb', 'devices'], capture_output=True, text=True)
                lines = result.stdout.strip().split('\n')[1:]
                current_devices = set()
                for line in lines:
                    if line.strip():
                        device_id = line.split()[0]
                        current_devices.add(device_id)
                
                if current_devices != self._devices:
                    self._devices = current_devices
                    self._notify_changes()
            except Exception as e:
                print(f"Error monitoring devices: {e}")
            time.sleep(1)  # 每秒检查一次

    def _notify_changes(self):
        devices_list = [{"id": device_id} for device_id in self._devices]
        for callback in self._callbacks:
            try:
                callback(devices_list)
            except Exception as e:
                print(f"Error in callback: {e}")

    def get_devices(self):
        return [{"id": device_id} for device_id in self._devices]

# 创建全局设备监视器实例
device_monitor = DeviceMonitor()
device_monitor.start()

def get_bing_wallpaper():
    """获取必应每日壁纸"""
    try:
        # 访问必应壁纸API
        bing_api = "https://www.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1"
        response = requests.get(bing_api)
        data = response.json()
        
        # 构建完整的图片URL
        image_url = "https://www.bing.com" + data["images"][0]["url"]
        return image_url
    except Exception as e:
        print(f"Error fetching Bing wallpaper: {e}")
        # 返回一个默认图片URL作为后备
        return "https://picsum.photos/1920/1080"

@app.route('/api/devices', methods=['GET'])
def get_devices():
    try:
        devices = device_monitor.get_devices()
        return jsonify({"devices": devices})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/api/install', methods=['POST'])
def install_aab():
    if 'file' not in request.files:
        return jsonify({"error": "No file provided"}), 400
    
    file = request.files['file']
    device_id = request.form.get('deviceId')
    
    if file.filename == '':
        return jsonify({"error": "No file selected"}), 400
    
    try:
        # Save uploaded file
        filename = secure_filename(file.filename)
        aab_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)
        file.save(aab_path)
        
        # Install AAB
        installer = AABInstaller()
        try:
            apks_path = installer.convert_to_apks(aab_path)
            installer.install_apks(apks_path, device_id)
        finally:
            # 确保清理临时文件
            try:
                if os.path.exists(aab_path):
                    os.remove(aab_path)
                if os.path.exists(apks_path):
                    os.remove(apks_path)
            except Exception as e:
                print(f"清理临时文件时出错: {e}")
        
        return jsonify({"message": "Installation successful"})
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.route('/bing-wallpaper', methods=['GET'])
def bing_wallpaper():
    try:
        image_url = get_bing_wallpaper()
        return {'url': image_url}
    except Exception as e:
        return {'error': str(e)}, 500

if __name__ == '__main__':
    app.run(debug=True, port=5000)